package com.teach.dto;

import java.util.ArrayList;
import java.util.List;


/**
 * - 分页结果
 * 
 * @author J.L.Zhou
 *
 * @param <T>
 *            当前页数据的类型
 */
public class PageDTO<T> {

	/**
	 * - 所有记录数
	 */
	private Long total;

	/**
	 *-  当前页数据
	 */
	private List<T> list;

	/**
	 * - 每页最大行数,默认：10
	 */
	private Integer rowMax;

	/**
	 * - 最大页码
	 */
	private Integer pageMax;

	/**
	 * - 当前页码
	 */
	private Integer current = 1;

	/**
	 * 
	 * @param total
	 *            所有记录数
	 * @param rowMax
	 *            每页最大行数
	 * @param current
	 *            当前页码
	 */
	public PageDTO(Long total, Integer current, Integer rowMax) {
		super();
		this.total = total;
		this.rowMax = rowMax;
		this.current = current;
		init();
	}

	private void init() {
		if (total == 0) {
			rowMax = 0;
			current = 1;
			pageMax = 0;
			return;
		}
		if (rowMax == null || rowMax < 1) {
			rowMax = 1;
		}
		if (current == null || current < 1) {
			current = 1;
		}

		pageMax = (int) (total - 1) / rowMax + 1;
		if (current > pageMax) {
			current = pageMax;
		}
	}

	/**
	 * 每页最大行数默认10
	 * 
	 * @param total
	 *            所有记录数
	 * @param current
	 *            当前页码
	 */
	public PageDTO(Long total, Integer current) {
		this(total, current, 10);
	}

	public Long getTotal() {
		return total;
	}

	public List<T> getList() {
		return list;
	}

	public PageDTO<T> setList(List<T> list) {
		this.list = list;
		return this;
	}

	public Integer getRowMax() {
		return rowMax;
	}

	public Integer getCurrent() {
		return current;
	}

	public Integer getPageMax() {
		return pageMax;
	}

	/**
	 * 获取记录偏移量
	 * 
	 * @return
	 */
	public Integer getOffset() {
		return (current - 1) * rowMax;
	}

	/**
	 * 获取当前页码前后的页面
	 * @param len 前后的页面的长度
	 * @return
	 */
	public List<Integer> getPages(int len) {
		if(len%2==0){//如果是偶数，当前页不好放到中间
			++len;
		}
		// 1:1 2 3 4 5 pageMax:100,current=1,len=5
		// 5:3 4 5 6 7
		// 100: 96 97 98 99 100
		// 98: 96 97 98 99 100
		// 95: 93 94 95 96 97
		// 1: 1 2 pageMax:2,current=1,len=5

		List<Integer> pages = new ArrayList<Integer>();
		if(total==0){
			return pages;
		}
		if (pageMax <= len) {
			for(int i=1;i<=pageMax;i++){
				pages.add(i);
			}
			return pages;
		}
		
		int start = current-(len/2);
		int end = current+(len/2);
		if(start<1){
			start = 1;
			end=start+len-1;
		}else if(end > pageMax){
			end = pageMax;
			start = pageMax-len+1;
		}
		for(int i=start;i<=end;i++){
			pages.add(i);
		}
		return pages;
	}
	public List<Integer> getPages(){
		return getPages(11);
	}

	@Override
	public String toString() {
		return "PageDTO [total=" + total + ", rowMax=" + rowMax + ", pageMax=" + pageMax
				+ ", current=" + current + ", list=" + list + "]";
	}
	
	
}
